#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题:实现一个优先级队列
问题: 怎样实现一个按优先级排序的队列？ 并且在这个队列上面每次 pop 操作总是返回优先级最高的那个元素
提示 : 
"""
import heapq


class PriorityQueue:
    '''实现了一个简单的优先级队列'''
    def __init__(self) -> None:
        self._queue = []
        self._index = 0     # 保证同等优先级元素的正确排序

    def push(self, item, priority) -> None:
        heapq.heappush(self._queue, (-priority, self._index, item))
        self._index += 1

    def pop(self):
        return heapq.heappop(self._queue)[-1]


class Item:
    def __init__(self, name) -> None:
        self.name = name

    def __repr__(self) -> str:
        return 'Item({!r})'.format(self.name)


def recipe1():
    '''PriorityQueue类的使用方式'''    
    q = PriorityQueue()
    q.push(Item('foo'), 4)
    q.push(Item('bar'), 5)
    q.push(Item('spam'), 4)
    q.push(Item('grok'), 1)

    print(f"{q.pop() = }")
    print(f"{q.pop() = }")
    print(f"{q.pop() = }")

def recipe2():
    '''元组比较'''
    a = (1, Item('foo'))
    b = (5, Item('bar'))
    print(f"{a < b = }")

    # 抛出异常
    # c = (1, Item('grok'))
    # print(a > b) 会

def main():
    print('recipe1'.center(20,'*'))
    recipe1()
    print('recipe2'.center(20,'*'))
    recipe2()


if __name__ == '__main__':
    main()
